/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.controller.glc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.dto.pf.BaseBusinessAuditDTO;
import com.plian.system.entity.pf.BaseBusinessAudit;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.glcydgz.IGlcBaseBusinessAuditService;
import com.plian.system.service.glcydgz.IGlcBusinessImportService;
import com.plian.system.service.pf.IBaseBusinessAuditService;
import com.plian.system.service.pf.IBusinessImportService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BaseBusinessAuditVO;
import com.plian.system.wrapper.pf.BaseBusinessAuditWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 经营业绩考核国资审核 控制器
 *
 * @author
 * @since 2019-09-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/glcBasebusinessaudit")
@Api(value = "BaseBusinessAuditController", tags = "经营业绩考核国资审核 控制器")
public class GlcBaseBusinessAuditController extends BaseController {

	private FormWorkflowService formWorkflowService;

	private IGlcBaseBusinessAuditService glcBaseBusinessAuditService;

	private BaseBusinessAuditWrapper baseBusinessAuditWrapper;

	private GzwProperties gzwProperties;

	private IGlcBusinessImportService glcBusinessImportService;

	@PostMapping(value = "/uploadFile",produces="application/json;charset=UTF-8")
	@ApiOperation(value = "导入", notes = "传入导入文件")
	public R uploadFile(@RequestParam("file") MultipartFile multipartFile){
		glcBusinessImportService.uploadFile(multipartFile);
		return R.success();
	}

	@PostMapping("/detail")
	@ApiOperation(value = "详情", notes = "传入 baseBusinessAudit")
	public R<BaseBusinessAuditVO> detail(@RequestBody BaseBusinessAudit baseBusinessAudit) {
		baseBusinessAudit.setModuleType(1);
		BaseBusinessAudit detail = glcBaseBusinessAuditService.getOne(Condition.getQueryWrapper(baseBusinessAudit));
		BaseBusinessAuditVO baseBusinessAuditVO = baseBusinessAuditWrapper.entityToVO(detail);
		return glcBaseBusinessAuditService.getDetailObj(baseBusinessAuditVO);
	}

	@PostMapping("/list")
	@ApiOperation(value = "分页", notes = "传入query")
	public ListResult<BaseBusinessAuditVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<BaseBusinessAudit> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BaseBusinessAudit()), entityList
		);
		queryWrapper.eq("module_type",1);
		String tokenOrgId = TokenUtil.getTokenOrgId();
		boolean flag = false;
		if (CollectionUtil.isEmpty(entityList)){
			flag = true;
		}else {
			for (SearchEntity entity:entityList){
				if ("filling_unit_id".equals(entity.getField())){
					flag = true;
				}
			}
		}
		if (flag && !(tokenOrgId.equals(gzwProperties.getId()) || tokenOrgId.equals(gzwProperties.getReportId()))){
			queryWrapper.eq("filling_unit_id",tokenOrgId);
		}
		IPage<BaseBusinessAudit> pages = glcBaseBusinessAuditService.page(Condition.getPage(query), queryWrapper);
		List<BaseBusinessAuditVO> baseBusinessAnnualVOS = baseBusinessAuditWrapper.entityToVO(pages.getRecords());
		ListResult<BaseBusinessAuditVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(baseBusinessAnnualVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@LogOperation("经营业绩考核国资审核-提交")
	@ApiOperation(value = "新增或修改", notes = "传入 baseBusinessAudit")
	public R<BaseBusinessAudit> submit(@Valid @RequestBody BaseBusinessAudit baseBusinessAudit) {
		baseBusinessAudit.setModuleType(1);
		String checkMessage = glcBaseBusinessAuditService.checkYear(baseBusinessAudit);
		if (StringUtil.isNotBlank(checkMessage)){
			return new R(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}

		boolean result = glcBaseBusinessAuditService.submit(baseBusinessAudit);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(baseBusinessAudit.getId()),baseBusinessAudit.getFormType(),processVariable);

		return result ? R.data(baseBusinessAudit) : new R(CommonCode.FAIL);
	}

	@PostMapping("/remove")
	@LogOperation("经营业绩考核国资审核-删除")
	@ApiOperation(value = "删除", notes = "传入 ids")
	public R remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return glcBaseBusinessAuditService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
				? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
	}

	@PostMapping("/getDetailByDto")
	@ApiOperation(value = "根据年度和填报时间获取基础表", notes = "传入 dto")
	public R<BaseBusinessAuditVO> getDetailByDto(@RequestBody BaseBusinessAuditDTO dto) {
		BaseBusinessAudit baseBusinessAudit = new BaseBusinessAudit();
		baseBusinessAudit.setFillingUnitId(dto.getFillingUnitId());
		baseBusinessAudit.setFillingYear(dto.getFillingYear());
		String checkMessage = glcBaseBusinessAuditService.checkYear(baseBusinessAudit);
		if (StringUtil.isNotBlank(checkMessage)){
			return new R(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}
		BaseBusinessAuditVO detailByDto = glcBaseBusinessAuditService.getDetailByDto(dto);
		if (Optional.ofNullable(detailByDto).isPresent()){
			return R.data(detailByDto);
		}else {
			return R.fail("未填写该企业 " + dto.getFillingYear() +" 年度调整，请先填写" );
		}
	}

	@PostMapping("/issued")
	@ApiOperation(value = "下发", notes = "传入 id")
	@LogOperation("经营业绩考核国资审核-下发")
	public R issued(@RequestBody BaseBusinessAudit baseBusinessAudit) {
		glcBaseBusinessAuditService.issued(baseBusinessAudit);
		return R.success();
	}

}
